<template>
  <div class="base-content">
    <div class="basic-info">
      <!-- <el-form ref="filterForm" :model="filterForm" inline>
        <el-form-item label="样品编号" prop="sampleNum">
          <el-input
            v-model="filterForm.sampleNum"
            placeholder="样品编号"
            clearable
          />
        </el-form-item>
        <el-form-item class="base-filter-button">
          <el-button type="primary" @click="getList('filter')">查询</el-button>
          <el-button @click="cancelForm">清空</el-button>
        </el-form-item>
      </el-form> -->
      <!--操作栏-->
      <div class="base-content-operate">
        <el-button
          v-rights="'BatchPrint'"
          icon="el-icon-plus"
          type="primary"
          @click="batchPrint"
          >批量打印</el-button
        >
        <el-button
          v-rights="'GenerateRecord'"
          type="primary"
          @click="generateElnTask"
          >生成ELN检测任务</el-button
        >
        <el-button
          v-loading="uploadLoad"
          type="primary"
          @click="exportStatistics"
          >导出样品统计表</el-button
        >
        <el-button
          v-loading="uploadLoad"
          type="primary"
          @click="exportConnectRecord"
          >导出样品交接记录</el-button
        >
      </div>

      <el-main class="roller_main">
        <div>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="我的样品" name="first"></el-tab-pane>
            <el-tab-pane label="全部样品" name="second"></el-tab-pane>
          </el-tabs>
        </div>
        <el-table
          ref="table"
          v-loading="tableLoad"
          class="filter unsetborder"
          :class="{ 'show-filter': showFilterRow }"
          height="calc(92%)"
          style="width: 100%"
          :data="tableData"
          highlight-current-row
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55">
            <el-table-column type="selection"></el-table-column>
          </el-table-column>
          <el-table-column align="center" width="50">
            <template #header>
              <div class="filter-icon" title="筛选">
                <SvgIcon
                  class-name="filter"
                  icon-class="filter"
                  @click="filterIconClick"
                />
              </div>
            </template>
            <el-table-column width="50"></el-table-column>
          </el-table-column>
          <el-table-column label="样品编号">
            <el-table-column prop="sampleNum">
              <template #header>
                <el-input
                  v-if="showFilterRow"
                  v-model="filterForm.sampleNum"
                  @keyup.enter.native="getList"
                ></el-input>
              </template>
              <template slot-scope="scope">
                <el-link type="primary" @click="toView(scope.row)">
                  {{ scope.row.sampleNum }}</el-link
                >
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="样品名称">
            <el-table-column prop="sampleName">
              <template #header>
                <el-input
                  v-if="showFilterRow"
                  v-model="filterForm.sampleName"
                  @keyup.enter.native="getList"
                ></el-input>
              </template>
            </el-table-column>
          </el-table-column>

          <!-- <el-table-column label="样品类别">
            <el-table-column prop="sampleCategoryName">
              <template #header>
                <el-input
                  v-if="showFilterRow"
                  v-model="filterForm.sampleCategoryName"
                  @keyup.enter.native="getList"
                ></el-input>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="检验类别">
            <el-table-column prop="samplingWayCodeName" width="100">
              <template #header>
                <el-select
                  ref="select"
                  v-model="filterForm.samplingWayCode"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in dicSamplingWayCodeList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table-column> -->
          <el-table-column label="检测项目">
            <el-table-column prop="detectionItemName">
              <template #header>
                <el-input
                  v-if="showFilterRow"
                  v-model="filterForm.detectionItemName"
                  @keyup.enter.native="getList"
                ></el-input>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="委托单号">
            <el-table-column prop="orderNum">
              <template #header>
                <el-input
                  v-if="showFilterRow"
                  v-model="filterForm.orderNum"
                  @keyup.enter.native="getList"
                ></el-input>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="委托单位">
            <el-table-column prop="unitName">
              <template #header>
                <el-input
                  v-if="showFilterRow"
                  v-model="filterForm.unitName"
                  @keyup.enter.native="getList"
                ></el-input>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="受检单位">
            <el-table-column prop="inspectedUnit">
              <template #header>
                <el-input
                  v-if="showFilterRow"
                  v-model="filterForm.inspectedUnit"
                  @keyup.enter.native="getList"
                ></el-input>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="状态">
            <el-table-column
              prop="sampleBusinessStatusCodeEnumName"
              width="100"
            >
              <template #header>
                <el-select
                  ref="select"
                  v-model="filterForm.sampleBusinessStatusCode"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in dicSampleStatusCodeList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
              <template slot-scope="scope">
                <el-link
                  v-if="
                    scope.row.sampleBusinessStatusCode != 40 &&
                    scope.row.sampleBusinessStatusCode != 50 &&
                    scope.row.sampleBusinessStatusCode != 51 &&
                    scope.row.sampleBusinessStatusCode != 60
                  "
                  type="primary"
                  @click="stateOperate(scope.row)"
                  >{{ scope.row.sampleBusinessStatusCodeEnumName }}</el-link
                ><span v-else>{{
                  scope.row.sampleBusinessStatusCodeEnumName
                }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="创建时间">
            <el-table-column prop="createTime" width="150">
              <template #header>
                <el-date-picker
                  v-model="filterForm.createTimeList"
                  type="datetimerange"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  align="right"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="样品管理状态">
            <el-table-column prop="sampleManageStatusCodeName" width="100">
              <template #header>
                <el-select
                  ref="select"
                  v-model="filterForm.sampleManageStatusCode"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in sampleManageStatusList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table-column>

          <!-- <el-table-column label="接收时间">
            <el-table-column prop="receivingDateString" width="150">
              <template #header>
                <el-date-picker
                  v-model="filterForm.sampleReceivingDateList"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm"
                  format="yyyy-MM-dd HH:mm"
                  align="right"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="['00:00:00', '23:59:59']"
                ></el-date-picker>
              </template>
            </el-table-column>
          </el-table-column>

          <el-table-column label="样品数量">
            <el-table-column prop="sampleCount"> </el-table-column>
          </el-table-column> -->

          <el-table-column label="操作" width="180">
            <el-table-column width="180">
              <template #header>
                <div v-if="showFilterRow" class="search-operate">
                  <el-link type="primary" @click="getList">搜索</el-link>
                  <el-link @click="cancelForm">清空</el-link>
                </div>
              </template>
              <template slot-scope="{ row }">
                <div class="base-table-operation">
                  <el-link v-rights="'Print'" type="primary" @click="print(row)"
                    >标签打印</el-link
                  >
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </el-main>
      <!-- <LodopHint :drawer.sync="drawer" /> -->
      <!--分页-->
      <BasePagination
        :total="total"
        :current-page="pagination.pageIndex"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
      <GenerateElnTaskDialog
        v-if="generateElnTaskVisible"
        ref="GenerateElnTaskDialog"
        :quote-label-visible.sync="generateElnTaskVisible"
        :sample-registration-id.sync="sampleRegistrationId"
      />
      <SampleDetailsDialog
        v-if="dialogFormVisible"
        ref="SampleDetailsDialog"
        :dialog-form-visible.sync="dialogFormVisible"
        :edit-id.sync="sampleInfoId"
      />

      <!-- <SampleRegistrationDialog
        v-if="dialogFormVisible"
        ref="SampleRegistrationDialog"
        :dialog-form-visible.sync="dialogFormVisible"
        :sample-registration-id.sync="sampleRegistrationId"
        :module-enable-entrust="moduleEnableEntrust"
        :read-only.sync="readOnly"
      /> -->
    </div>
    <el-dialog
      v-toggle-full
      class="base-dialog"
      :custom-class="'panna-dialog_small'"
      title="设置标签大小"
      :append-to-body="true"
      :visible.sync="innerDialogFormVisible"
      :before-close="handleClose"
      ><el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="宽" prop="labelWidth">
          <el-input
            v-model="form.labelWidth"
            size="small"
            onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)"
            onafterpaste="this.value=this.value.match(/\d+\.?\d{0,2}/)"
            maxlength="9"
          ></el-input>
        </el-form-item>
        <el-form-item label="高" prop="labelHeight">
          <el-input
            v-model="form.labelHeight"
            size="small"
            onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)"
            onafterpaste="this.value=this.value.match(/\d+\.?\d{0,2}/)"
            maxlength="9"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="base-dialog-footer">
        <el-button type="primary" @click="onSubmit('form')">确定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </span>
    </el-dialog>
    <div
      id="printDiv"
      ref="printDiv"
      style="display: none; width: 60mm; height: 40mm"
    >
      <div
        v-for="(item, index) in printData"
        :key="index"
        style="display: flex; flex-direction: column; align-items: center"
      >
        <img
          :src="item | creatBarCode(item, form.labelHeight, form.labelWidth)"
          style="max-width: 100%; max-height: 100%"
        />
      </div>
    </div>
    <iframe
      ref="printIframe"
      frameborder="0"
      scrolling="no"
      style="margin: 0px; padding: 0px; width: 0px; height: 0px"
    ></iframe>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
// import SampleRegistrationDialog from "../SampleRegistration/SampleRegistrationDialog.vue";
import SampleDetailsDialog from "./SampleDetailsDialog.vue";
import { sampleManageList } from "../../../api/SampleManage/SampleRegistration";
import {
  DownloadExportWord,
  SampleWord,
} from "../../../api/SampleManage/Export";
import {getDictList} from "@/ModuleSystem/api/System/SystemDict.js";
import BarcodeJs from "jsbarcode";
import {
  ExportExcel,
  DownloadExportExcel,
} from "../../../api/SampleManage/Export";
import GenerateElnTaskDialog from "./GenerateElnTaskDialog.vue";
// import { getLodop } from "@/utils/LodopFuncs";
export default {
  name: "SampleManageList",
  components: {
    // SampleRegistrationDialog,
    GenerateElnTaskDialog,
    SampleDetailsDialog,
  },
  filters: {
    creatBarCode(barCodeData, num, labelHeight, labelWidth) {
      console.log("触发条码生成事件");
      const canvas = document.createElement("canvas");
      BarcodeJs(canvas, barCodeData, {
        format: "CODE128",
        displayValue: true,
        // height: 165,
        // width: 2,
        height: labelHeight,
        width: labelWidth,
        textAlign: "center",
        font: "cursive",
        fontOptions: "bold",
        fontSize: 30,
        textMargin: 3,
      });
      return canvas.toDataURL("image/png");
    },
  },
  data() {
    return {
      activeName: "first",
      sampleRegistrationId: "",
      sampleInfoId: "",
      generateElnTaskVisible: false,
      readOnly: true,
      dialogFormVisible: false,
      innerDialogFormVisible: false,
      drawer: false,
      tableLoad: false,
      showFilterRow: false,
      uploadLoad: false,
      dicSamplingWayCodeList: [],
      dicSampleStatusCodeList: [],
      sampleManageStatusList: [
        {
          name: "全部",
          value: "-1",
        },
        {
          name: "待接收",
          value: "1",
        },
        {
          name: "待领取",
          value: "3",
        },
        {
          name: "使用中",
          value: "10",
        },
        {
          name: "已留存",
          value: "20",
        },
        {
          name: "已报废",
          value: "40",
        },
      ],
      printData: [],
      tableData: [],
      tableDatas: [],
      pagination: {
        pageIndex: 1,
        pageSize: 10,
      },
      total: 0,
      filterForm: {
        sampleIdList: "",
        orderNum: "",
        sampleNum: "",
        sampleName: "",
        sampleCategoryName: "",
        samplingWayCode: "-1",
        detectionItemName: "",
        unitName: "",
        inspectedUnit: "",
        sampleManageStatusCode: "-1",
        sampleBusinessStatusCode: "-1",
        createTimeList: [],
        createTimeState: null,
        createTimeEnd: null,
        sampleReceivingDateList: [],
        activeUserData: true,
      },
      form: {
        labelWidth: "2",
        labelHeight: "165",
      },
      sampleNumList: "",
      rules: {
        labelWidth: [
          { required: true, message: "请输入宽度", trigger: "blur" },
        ],
        labelHeight: [
          { required: true, message: "请输入高度", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["moduleEnableEntrust"]),
  },
  created() {
    var sampleNumList = this.$route.query.sampleNumList;
    if (sampleNumList !== undefined) {
      if (sampleNumList !== "") {
        this.activeName = "second";
        this.filterForm.activeUserData = false;
        this.filterForm.sampleNumList = sampleNumList;
      }
    }

   getDictList({ dictCode: "SamplingWayCode" })
      .then((res) => {
        this.dicSamplingWayCodeList = res.data;
        var obj = {};
        obj.id = "-1";
        obj.value = "-1";
        obj.name = "全部";
        this.dicSamplingWayCodeList.unshift(obj);
      });
    getDictList({ dictCode: "SampleStatus" })
      .then((res) => {
        this.dicSampleStatusCodeList = res.data;
        var obj = {};
        obj.id = "-1";
        obj.value = "-1";
        obj.name = "全部";
        this.dicSampleStatusCodeList.unshift(obj);
      });

    this.getList();
  },
  methods: {
    // 交接记录
    exportConnectRecord() {
      var idList = [];
      for (let i = 0; i < this.tableDatas.length; i++) {
        idList.push(this.tableDatas[i].sysBusinessSampleInfoId);
      }

      SampleWord({ id: idList, exportWordTypeEnum: 7 }).then((res) => {
        DownloadExportWord({ path: res.data, exportWordTypeEnum: 7 }).then(
          (res) => {
            var blob = new Blob([res.data], {
              type: "application/octet-stream",
            });
            var url = window.URL.createObjectURL(blob);
            const link = document.createElement("a"); // 创建a标签
            link.href = url;
            link.download = "样品交接记录模板.docx"; // 重命名文件
            link.click();
            URL.revokeObjectURL(url); // 释放内存
          }
        );
      });
    },
    // 点击状态
    stateOperate(row) {
      // 点击待接收跳转到样品接收页面，并筛选出该样品对应的样品接收任务
      if (Number(row.sampleBusinessStatusCode) === 10) {
        this.$router.push({
          path: "/SampleReceivingList",
          query: { sampleRegistrationId: row.id },
        });
      } else if (Number(row.sampleBusinessStatusCode) === 20) {
        // 点击任务待分配跳转到任务分配页面
        this.$router.push({
          path: "/EntrustTaskList",
          query: { sampleRegistrationId: row.id },
        });
      } else if (Number(row.sampleBusinessStatusCode) === 21) {
        // 点击任务待接收跳转到任务接收页面
        this.$router.push({
          path: "/EntrustTaskReceive",
          query: { sysBusinessSampleInfoId: row.sysBusinessSampleInfoId },
        });
      } else if (Number(row.sampleBusinessStatusCode) === 30) {
        // 点击待领取跳转到样品领取
        this.$router.push({
          path: "/SampleCollectionList",
          query: { sampleRegistrationId: row.id },
        });
      }
    },
    handleClick() {
      if (this.activeName === "first") {
        this.filterForm.activeUserData = true;
      } else {
        this.filterForm.activeUserData = false;
      }
      this.pagination.pageIndex = 1;

      this.getList();
    },
    // 生成eln任务
    generateElnTask() {
      if (
        this.tableDatas === undefined ||
        this.tableDatas === null ||
        this.tableDatas.length === 0
      ) {
        this.$message.error("请选择数据");
        return false;
      }
      if (this.tableDatas.length > 1) {
        this.$message.error("最多可选一条数据");
        return false;
      }
      if (
        this.tableDatas[0].sampleBusinessStatusCode !== 20 &&
        this.tableDatas[0].sampleBusinessStatusCode !== 30 &&
        this.tableDatas[0].sampleBusinessStatusCode !== 40
      ) {
        this.$message.error(
          "请选择状态为【待分配】、【待领取】、【领取完成】的样品"
        );
        return false;
      }

      this.sampleRegistrationId = this.tableDatas[0].id;
      this.generateElnTaskVisible = true;
    },
    toView(row) {
      this.sampleInfoId = row.sysBusinessSampleInfoId;
      this.dialogFormVisible = true;
    },
    // 导出统计表
    exportStatistics() {
      this.uploadLoad = true;
      ExportExcel(this.filterForm)
        .then((res) => {
          DownloadExportExcel({ path: res.data, exportWordTypeEnum: 2 })
            .then((res) => {
              this.uploadLoad = false;
              var blob = new Blob([res.data], {
                type: "application/octet-stream",
              });
              var url = window.URL.createObjectURL(blob);
              const link = document.createElement("a"); // 创建a标签
              link.href = url;
              link.download = "样品统计.xlsx"; // 重命名文件
              link.click();
              URL.revokeObjectURL(url); // 释放内存
            })
            .catch(() => {
              this.uploadLoad = false;
            });
        })
        .catch(() => {
          this.uploadLoad = false;
        });
    },
    filterIconClick() {
      this.showFilterRow = !this.showFilterRow;
      !this.showFilterRow && this.cancelForm();
    },
    onSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          // if (this.form.labelWidth.indexOf("mm") === -1) {
          //   this.form.labelWidth = this.form.labelWidth + "mm";
          // }
          // if (this.form.labelHeight.indexOf("mm") === -1) {
          //   this.form.labelHeight = this.form.labelHeight + "mm";
          // }
          this.printTag(this.sampleNumList);
        }
      });
    },
    handleClose() {
      this.innerDialogFormVisible = false;
      this.getList();
    },
    // 标签打印
    printTag(data) {
      this.printData = data;
      this.$nextTick(() => {
        var printIframe = this.$refs.printIframe;
        var html = this.$refs.printDiv.innerHTML;
        printIframe.setAttribute("srcdoc", html);
        printIframe.onload = function() {
          // 去掉iframe里面的dom的body的padding margin的默认数值
          printIframe.contentWindow.document.body.style.padding = "0px";
          printIframe.contentWindow.document.body.style.margin = "0px";
          // 开始打印
          printIframe.contentWindow.focus();
          printIframe.contentWindow.print();
        };
      });
    },
    // 标签打印
    // printTag(data) {
    //   var LODOP = getLodop();
    //   if (!LODOP) {
    //     this.drawer = true;
    //     return false;
    //   }
    //   LODOP.SET_LICENSES(
    //     "",
    //     "EE0887D00FCC7D29375A695F728489A6",
    //     "C94CEE276DB2187AE6B65D56B3FC2848",
    //     ""
    //   );
    //   LODOP.PRINT_INIT("条形码");
    //   for (let i = 0; i < data.length; i++) {
    //     LODOP.SET_PRINT_PAGESIZE(
    //       1,
    //       this.form.labelWidth,
    //       this.form.labelHeight
    //     );
    //     LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT", "Full-Page");
    //     LODOP.SET_PRINT_MODE("FULL_HEIGHT_FOR_OVERFLOW", true);
    //     // 字号
    //     LODOP.SET_PRINT_STYLE("FontSize", 8);
    //     LODOP.SET_PRINT_STYLE("Bold", 1);
    //     // 条形码
    //     LODOP.ADD_PRINT_BARCODE(40, 23, "40mm", 85, "128Auto", data[i]);
    //     LODOP.SET_PRINT_STYLEA(0, "AlignJustify", 2);
    //     // 预览框大小
    //     LODOP.SET_PREVIEW_WINDOW(2, 0, 0, "500px", "400px");
    //     // 分页
    //     LODOP.NewPage();
    //   }
    //   // 隐藏打印按钮
    //   LODOP.SET_SHOW_MODE("HIDE_PBUTTIN_SETUP", true);
    //   LODOP.PREVIEW();
    // },
    batchPrint() {
      this.sampleNumList = [];
      var data = [];
      for (let i = 0; i < this.tableDatas.length; i++) {
        data.push(this.tableDatas[i].sampleNum);
      }
      this.sampleNumList = data;
      // this.printTag(data);
      this.form.labelWidth = "2";
      this.form.labelHeight = "165";
      // this.printTag(this.sampleNumList)
      this.innerDialogFormVisible = true;
    },
    print(row) {
      this.sampleNumList = [];
      var data = [];
      data.push(row.sampleNum);
      this.sampleNumList = data;
      this.form.labelWidth = "2";
      this.form.labelHeight = "165";
      // this.printTag(this.sampleNumList)

      this.innerDialogFormVisible = true;
      // this.printTag(data);
    },
    // 设置标签大小单位mm
    setSize() {},
    changePage(page) {
      this.pagination.pageIndex = page;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    // 多选
    handleSelectionChange(val) {
      this.tableDatas = val;
    },
    // 查询
    getList(flag) {
      if (
        this.filterForm.createTimeList !== null &&
        this.filterForm.createTimeList.length !== 0
      ) {
        this.filterForm.createTimeState =
          this.filterForm.createTimeList[0] + " 00:00:00";
        this.filterForm.createTimeEnd =
          this.filterForm.createTimeList[1] + " 23:59:59";
      }
      if (flag) {
        this.pagination.pageIndex = 1;
      }
      sampleManageList({ ...this.filterForm, ...this.pagination }).then(
        (res) => {
          this.tableData = res.data.dataList;
          this.total = res.data.total;
        }
      );
    },
    // 清空
    cancelForm() {
      this.filterForm = this.$options.data().filterForm;
      this.handleClick();
    },
  },
};
</script>
